<template>
  <div>
    <el-card v-if="records.length > 0"
             style="text-align: right; margin-bottom: 20px">
      <!--   -->
      <upload v-if="!importResult"
              style="margin-right: 20px"
              :api="api"
              :btn-loading.sync="loading"
              @upload="upload" />
      <el-button v-if="!importResult"
                 :disabled="submitDisabled && cloneRecords.length > 0 || cloneRecords.length == 0"
                 :loading="loading"
                 type="primary"
                 @click="loading = true; handleSubmit()">确认导入</el-button>
      <el-button v-if="!importResult"
                 @click="back"> 返 回</el-button>
    </el-card>
    <el-card class="table-box">
      <!--  <table-pagination-box :records.sync="cloneRecords"
                            :columns="columns"
                            :isResult="isResult"
                            @submitDisabled="submitIsDisabled" /> -->
      <el-table :data="pageList"
                tooltip-effect="dark"
                class="table-style"
                height="750"
                border>
        <!-- v-loading="loading" -->
        <el-table-column label="#"
                         type="index"></el-table-column>
        <template v-for="(column, index) in columns">
          <table-column-import :key="index"
                               v-bind="column"
                               :type="column.type"
                               @updated="handleUpdated(column, arguments)" />
        </template>
        <el-table-column label="状态"
                         fixed="right"
                         width="80px">
          <template slot-scope="scope">
            <!-- !isResult?scope.row.errors.length:false -->
            <validate-status :status="!scope.row.errors.length" />
          </template>
        </el-table-column>
        <el-table-column :label="!isResult ? '提示' : '原因'"
                         fixed="right"
                         width="150">
          <template slot-scope="scope">
            <tip-message :value="scope.row.errors" />
          </template>
        </el-table-column>
        <el-table-column width="80"
                         fixed="right"
                         label="操作"
                         align="center">
          <template slot-scope="scope">
            <el-button v-show="!isResult && !available(scope.row)"
                       type="default"
                       size="mini"
                       icon="el-icon-delete"
                       @click="handleRemove(scope.$index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total"
                     :page-sizes="pageSizeOptions"
                     :page-size.sync="size"
                     :current-page.sync="page"
                     @size-change="currentPage"
                     @current-change="currentPage">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import TableColumnImport from "./TableColumnImport.vue";
import ValidateStatus from "./ValidateStatus.vue";
import TipMessage from "./TipMessage.vue";
import upload from "./UploadExcel.vue";
import _ from "lodash";

export default {
  name: "TableBoxImport",
  components: { TableColumnImport, ValidateStatus, TipMessage, upload },
  props: {
    columns: {
      type: Array,
      default () {
        return [
          {
            type: "index",
            label: "#"
          },
          {
            name: "carrierName",
            label: "承运方名称",
            type: "input"
          },
          {
            name: "contactName",
            label: "联系人",
            type: "input"
          },
          {
            name: "contactMobile",
            label: "联系电话",
            type: "input"
          }
        ];
      }
    },
    api: {
      type: Object
    },
    records: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      size: 10,
      page: 1,
      total: 0,
      isResult: false,
      importResult: false,
      pageList: [],
      loading: false,
      pageSizeOptions: [10, 20, 50, 100],
      cloneRecords: [],
      allListLength: 0,
      errorList: []
    };
  },
  computed: {
    available () {
      return (row) => !row.errors.length || row.$changed;
    },
    errorRecords () {
      return this.cloneRecords.filter((record) => !this.available(record));
    },
    errorSize () {
      return this.errorRecords.length;
    },
    submitDisabled () {
      return this.errorSize > 0;
    },
    column () {
      return (name) => this.columns.filter((column) => column.name === name);
    }
  },
  watch: {
    records: {
      immediate: true,
      handler (val) {
        this.watchList(val);
        this.currentPage();
      }
    }
  },
  created () {
    this.watchList(this.records);
  },
  methods: {
    // 监听table数据然后处理
    watchList (data) {
      this.cloneRecords = data
        .map((record) => {
          return {
            ...record,
            disabled: this.available(record),
            sort: !record.errors.length ? 1 : 0
          };
        })
        .sort((a, b) => a.sort - b.sort);
    },
    // 返回
    back () {
      this.$router.back();
    },
    // 分页
    currentPage () {
      this.total = this.cloneRecords.length;
      this.pageList = this.cloneRecords.slice(
        (this.page - 1) * this.size,
        this.page * this.size
      );
    },
    upload (data) {
      this.cloneRecords = data;
      this.watchList(data);
      this.currentPage();
      this.isResult = false;
    },
    // 修改错误数据改变状态
    handleUpdated (column, [{ index }]) {
      let record = this.cloneRecords[index];
      this.$set(record, "$changed", true);
    },
    // 删除
    handleRemove (index) {
      if (this.page > 1) {
        this.cloneRecords.splice((this.page - 1) * this.size + index, 1)
      } else {
        this.cloneRecords.splice(index, 1)
      }
      // (除第一页外) 每次删除可能会把当前这一页的数据删除完，这时候需要请求上一页的数据
      if (this.cloneRecords.length >= this.size && this.cloneRecords.length % this.size === 0) {
        if (this.page != 1) {
          this.page = this.page - 1
        }
      }
      this.currentPage()
    },
    handleSubmit: _.debounce(function () {    // 触发事件
      this.submit();
    }, 600),
    // 提交数据
    async submit () {
      if (this.errorSize > 0) {
        this.loading = false;
        return this.$message({ type: "error", message: "请先修改错误数据" });
      }
      const fullscreenLoading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      this.allListLength = this.cloneRecords.length;
      let { code, data, message } = await this.api.batchInsert(
        this.cloneRecords
      ).catch(err => {
        fullscreenLoading.close();
        this.$emit("update:btnLoading", false);
        this.loading = false;
        console.log(err);
      });
      fullscreenLoading.close();
      let errorList = data.filter((item) => {
        return item.errors.length > 0;
      });
      if (errorList.length <= 0) {
        this.watchList(errorList);
        this.$message.success(message);
        this.back();
      } else {
        this.cloneRecords = data;
        this.isResult = false;
        this.importResult = false;
        // this.pageList = [];
        // this.cloneRecords = data.map((record) => {
        //   return {
        //     ...record,
        //     disabled: this.available(record)
        //   };
        // });
        // if (data.find(item => item.errors.length)) this.cloneRecords = [];
        // this.isResult = true;
      }
      this.currentPage();
      this.loading = false;
    }
  }
};
</script>
